import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login/index.vue'),
      meta: { title: '登录 - 酱梨管理' }
    },
    {
      path: '/',
      name: 'Layout',
      component: () => import('@/views/Layout/index.vue'),
      redirect: '/home',
      children: [
        // 首页
        {
          path: '/home',
          name: 'Home',
          component: () => import('@/views/Home/index.vue'),
          meta: { title: '首页 - 酱梨管理' }
        },
        // 数据管理
        {
          path: '/user',
          name: 'UserList',
          component: () => import('@/views/User/index.vue'),
          meta: { title: '用户列表 - 酱梨管理' }
        },
        {
          path: '/merchant',
          name: 'MerchantList',
          component: () => import('@/views/Merchant/index.vue'),
          meta: { title: '商家列表 - 酱梨管理' }
        },
        {
          path: '/dish',
          name: 'DishList',
          component: () => import('@/views/Dish/index.vue'),
          meta: { title: '菜品列表 - 酱梨管理' }
        },
        {
          path: '/ingredient',
          name: 'IngredientList',
          component: () => import('@/views/Ingredient/index.vue'),
          meta: { title: '食材列表 - 酱梨管理' }
        },
        // 用户反馈
        {
          path: '/feedback',
          name: 'Feedback',
          component: () => import('@/views/Feedback/index.vue'),
          meta: { title: '用户反馈 - 酱梨管理' }
        },
        //编辑信息
        {
          path: '/editInfo',
          name: 'EditInfo',
          component: () => import('@/views/EditInfo/index.vue'),
          meta: { title: '编辑信息 - 酱梨管理' }
        }
      ]
    }
  ]
})

router.beforeEach((to) => {
  //如果没有token,切访问的是非登录页就跳转到登录页
  const userStore = useUserStore()
  if (!userStore.token && to.path !== '/login') {
    ElMessage.warning('请先登录')
    return '/login'
  }
  //设置页面标题
  document.title = to.meta.title || '酱梨管理'
  return true
})

export default router
